package com.chhuang.ewcrm.ctrl;

import com.browniebytes.javafx.control.DateTimePicker;
import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.api.AppRequest;
import com.chhuang.ewcrm.api.ServiceRxSchedulers;
import com.chhuang.ewcrm.api.ServiceSubscriber;
import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.bean.StatusBean;
import com.chhuang.ewcrm.bean.TableColumnBean;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WCustomerDao;
import com.chhuang.ewcrm.dao.WLicensePlateDao;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.*;
import com.chhuang.ewcrm.utils.*;
import com.github.pagehelper.PageInfo;
import com.jfoenix.controls.JFXButton;
import javafx.beans.property.ObjectProperty;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;

import static javafx.application.Platform.runLater;

/**
 * @author chhuang
 * @create 2020-11-21-15:31
 */
public class ReportTransferController implements Initializable {
    private final Logger logger = LoggerFactory.getLogger(ReportTransferController.class);

    @FXML
    private TextField numberTextField;
    @FXML
    private TextField lprTextField;
    @FXML
    private TextField warehouseTextField;
    @FXML
    private TextField warehouse1TextField;
    @FXML
    private TextField goodsTextField;
    @FXML
    private TextField goods1TextField;
    @FXML
    private TextField chargemanTextField;
    @FXML
    private TextField grossWeightTextField;
    @FXML
    private TextField tareWeightTextField;
    @FXML
    private TextField impurityWeightTextField;
    @FXML
    private TextField netWeightTextField;
    @FXML
    private TextField priceTextField;
    @FXML
    private TextField deductionMoneyTextField;
    @FXML
    private TextField amountTextField;
    @FXML
    private TextField remarkTextField;
    @FXML
    private TextField statusTextField;
    @FXML
    private TextField enterTimeTextField;
    @FXML
    private TextField outTimeTextField;
    @FXML
    private JFXButton printJFXButton;
    @FXML
    private JFXButton delJFXButton;

    @FXML
    private TextField queryNumberTextField;
    @FXML
    private ComboBox<String> queryLprComboBox;
    @FXML
    private ComboBox<String> queryWarehouseComboBox;
    @FXML
    private ComboBox<String> queryWarehouse1ComboBox;
    @FXML
    private ComboBox<String> queryGoodsComboBox;
    @FXML
    private ComboBox<String> queryGoods1ComboBox;
    @FXML
    private ComboBox<String> queryChargemanComboBox;
    @FXML
    private ComboBox<StatusBean> queryStautsComboBox;
    @FXML
    private DateTimePicker enterTimeStartPicker;
    private ObjectProperty<LocalDateTime> enterTimeStart;
    @FXML
    private DateTimePicker enterTimeEndPicker;
    private ObjectProperty<LocalDateTime> enterTimeEnd;
    @FXML
    private JFXButton seachJFXButton;
    @FXML
    private JFXButton exportButton;

    @FXML
    private TableView<ETransfer> tableView;
    @FXML
    private ChoiceBox<Integer> pageSizeChiceBox;
    @FXML
    private Label pagesLabel;
    @FXML
    private Label totalLabel;
    @FXML
    private Pagination pagination;

    private ETransfer eTransferBinder = null;
    private final QueryBean<ETransfer> queryBean = new QueryBean<>();

    private final NumberTextFilter numberTextFilter = new NumberTextFilter();
    private final WLicensePlateDao wLicensePlateDao = App.getSession().getMapper(WLicensePlateDao.class);
    private final WCustomerDao wCustomerDao = App.getSession().getMapper(WCustomerDao.class);

    private TableColumnBean[] tableColumnBeans = {
            new TableColumnBean("码单号","transferNumber", true),
            new TableColumnBean("车牌号","licensePlate"),
            new TableColumnBean("仓库","warehouseName", true),
            new TableColumnBean("原仓库","warehouse1Name"),
            new TableColumnBean("物品","goodsName", true),
            new TableColumnBean("物品原名","goods1Name", true,false),
            new TableColumnBean("毛重","grossWeight"),
            new TableColumnBean("皮重","tareWeight"),
            new TableColumnBean("扣重","impurityWeight"),
            new TableColumnBean("净重","netWeight"),
            new TableColumnBean("价格","price"),
            new TableColumnBean("扣款","deductionMoney"),
            new TableColumnBean("金额","paymentAmount"),
            new TableColumnBean("过磅员","weighmanName", true),
            new TableColumnBean("负责人","chargemanName", true, false),
            new TableColumnBean("状态","status", true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    Integer status = (Integer) o;
                    return showStatus(status);
                }
            },
            new TableColumnBean("进厂时间","enterTime", true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.YYYY_MM_DD_HH_MM_SS);
                }
            },
            new TableColumnBean("出厂时间","outTime", true, false){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.YYYY_MM_DD_HH_MM_SS);
                }
            }
    };

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        initTable();
        initLicensePlate();
        initWarehouse();
        initGoods();
        initMans();
        initStatus();
        initDateTime();
        initListener();
    }

    private void initLicensePlate() {
        List<WLicensePlate> wLicensePlateList = wLicensePlateDao.query(null);
        if(wLicensePlateList!=null && !wLicensePlateList.isEmpty()){
            for(WLicensePlate lp : wLicensePlateList){
                queryLprComboBox.getItems().add(lp.getWlpNumber());
            }
            new AutoCompleteComboBoxListener<>(queryLprComboBox);
        }
        queryLprComboBox.getEditor().setTextFormatter(new TextFormatter<>(new UpCastTextFilter()));
    }

    private void initWarehouse() {
        AppRequest.getInstance().getService().getWarehouses()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取所有仓库请求") {
                    @Override
                    protected void onHandleSuccess(List<EWarehouse> warehouses) {
                        if(warehouses!=null && !warehouses.isEmpty()) {
                            runLater(()->{
                                for(EWarehouse temp: warehouses){
                                    queryWarehouseComboBox.getItems().add(temp.getWarehouseName());
                                    queryWarehouse1ComboBox.getItems().add(temp.getWarehouseName());
                                }
                            });
                        }
                    }
                });
    }

    private void initGoods() {
        for (int i=0;i<3;i++) {
            AppRequest.getInstance().getService().getGoods(i, null)
                    .compose(ServiceRxSchedulers.compose())
                    .subscribe(new ServiceSubscriber<>("获取物品"+i) {
                        @Override
                        protected void onHandleSuccess(List<EGoods> eGoodsList) {
                            if(eGoodsList!=null && !eGoodsList.isEmpty())
                                eGoodsList.forEach(item->
                                        runLater(()->{
                                            queryGoodsComboBox.getItems().add(item.getGoodsName());
                                            queryGoods1ComboBox.getItems().add(item.getGoodsName());
                                        })
                                );
                        }
                    });
        }
    }

    private void initMans() {
        AppRequest.getInstance().getService().getChargerMans()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取负责人请求") {
                    @Override
                    protected void onHandleSuccess(List<SysUser> users) {
                        if(users!=null && !users.isEmpty()) {
                            runLater(()-> {
                                for(SysUser user : users){
                                    queryChargemanComboBox.getItems().add(user.getFullname()==null?user.getUsername():user.getFullname());
                                }
                                new AutoCompleteComboBoxListener<>(queryChargemanComboBox);
                            });
                        }
                    }
                });
    }

    private void initStatus() {
        queryStautsComboBox.getItems().addAll(
                new StatusBean(null,"--请选择--"),
                new StatusBean(0,"作废"),
                new StatusBean(1,"过磅完成"),
                new StatusBean(2,"确认完成"));
        queryStautsComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(StatusBean statusBean) {
                return statusBean==null?null:statusBean.getStatus();
            }

            @Override
            public StatusBean fromString(String s) {
                return null;
            }
        });
    }

    private void initDateTime() {
        enterTimeStartPicker.setPopupPreWidth(enterTimeStartPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        enterTimeStart = enterTimeStartPicker.dateTimeProperty();
        enterTimeEndPicker.setPopupPreWidth(enterTimeEndPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        enterTimeEnd = enterTimeEndPicker.dateTimeProperty();
    }

    private void initListener() {
        //每页显示多少条数据选择器监听
        pageSizeChiceBox.getSelectionModel().selectedItemProperty().addListener((observableValue, integer, t1) -> {
            queryBean.setPageSize(t1);
            getTableData();
        });

        //点击分页按钮监听
        pagination.currentPageIndexProperty().addListener((observableValue, number, t1) -> {
            queryBean.setPageNum(t1.intValue()+1);
            getTableData();
        });

        //点击打印
        printJFXButton.setOnAction(event -> {
            if(eTransferBinder!=null && StringUtils.isNotEmpty(eTransferBinder.getTransferId())){
                //打印过磅记录
                String reportPath = MyPath.getJasperPath()+"ETransfer.jasper";
                //isUseFieldDescription 默认为true, 为true时会用description对应的值获取javabean的属性
                JRBeanArrayDataSource beanArrayDataSource = new JRBeanArrayDataSource(new ETransfer[]{eTransferBinder});
                try {
                    //模板中填充数据 参数 模板地址， Map中为parameters对应的内容这里没有， datasource
                    JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap<>(), beanArrayDataSource);
                    JasperPrintManager.printReport(jasperPrint, false);//直接打印
                    String pdfPath = MyPath.getJasperPath()+"ETransfer.pdf";
                    JasperExportManager.exportReportToPdfFile(jasperPrint, pdfPath);//导出pdf
                    Runtime.getRuntime().exec("rundll32 url.dll FileProtocolHandler "+ pdfPath);//打开预览pdf
                } catch (JRException | IOException e) {
                    e.printStackTrace();
                }
            }else {
                MyAlert.showAlert("提示","没有选中要打印的过磅记录","请先双击表格中某一行要打印的过磅记录");
            }
        });

        //点击删除
        delJFXButton.setOnAction(event -> {
            if(eTransferBinder!=null && StringUtils.isNotEmpty(eTransferBinder.getTransferId())){
                if(Constants.loginUser!=null && //用户已登录
                        ("001".equals(Constants.loginUser.getRoleId())) || //是管理员
                        Constants.loginUser.getUserId().equals(eTransferBinder.getWeighmanId())) { //是本条过磅记录的过磅员
                    String remark = null;

                    while (StringUtils.isEmpty(remark)){
                        Optional<String> result = MyAlert.getInputDialog("备注","您确定要将此记录作废吗？","作废原因：");
                        if (result.isPresent()){
                            remark = result.get();
                            if(StringUtils.isNotEmpty(remark)){
                                //修改状态为作废0
                                AppRequest.getInstance().getService().toInvalidTransfer(eTransferBinder.getTransferId(), remark)
                                        .compose(ServiceRxSchedulers.compose())
                                        .subscribe(new ServiceSubscriber<>("作废内部周转记录") {
                                            @Override
                                            protected void onHandleSuccess(Void aVoid) {
                                                runLater(()->{
                                                    MyAlert.showAlert("成功","内部周转记录已作废","");
                                                    getTableData();
                                                    resetForm();
                                                });
                                            }
                                        });
                            }else{
                                MyAlert.showError("错误","作废原因不能为空","请一定要输入作废原因");
                            }
                        }else {
                            remark = "cancel";
                        }
                    }
                }else {
                    MyAlert.showWarn("警告", "你不是管理员，且这条过磅记录不是当前用户操作的", "要把这条记录作废，请联系管理员，或者这条记录的过磅员");
                }
            }else {
                MyAlert.showAlert("提示","没有选中要作废的过磅记录","请先双击表格中某一行要作废的过磅记录");
            }
        });

        //查询
        seachJFXButton.setOnAction(event -> {
            ETransfer eTransfer = new ETransfer();

            eTransfer.setTransferNumber(queryNumberTextField.getText());
            eTransfer.setLicensePlate(StringUtils.isEmpty(queryLprComboBox.getValue())?null:queryLprComboBox.getValue());
            eTransfer.setWarehouseName(StringUtils.isEmpty(queryWarehouseComboBox.getValue())?null:queryWarehouseComboBox.getValue());
            eTransfer.setWarehouse1Name(StringUtils.isEmpty(queryWarehouse1ComboBox.getValue())?null:queryWarehouse1ComboBox.getValue());
            eTransfer.setGoodsName(StringUtils.isEmpty(queryGoodsComboBox.getValue())?null:queryGoodsComboBox.getValue());
            eTransfer.setGoods1Name(StringUtils.isEmpty(queryGoods1ComboBox.getValue())?null:queryGoods1ComboBox.getValue());
            eTransfer.setChargemanName(StringUtils.isEmpty(queryChargemanComboBox.getValue())?null:queryChargemanComboBox.getValue());
            eTransfer.setStatus(queryStautsComboBox.getValue()==null?null:queryStautsComboBox.getValue().getCode());

            if(!enterTimeStartPicker.isVoid())
                eTransfer.setEnterTimeStart(DateUtil.localDateTime2Date(enterTimeStart.get()));
            if(!enterTimeEndPicker.isVoid())
                eTransfer.setEnterTimeEnd(DateUtil.localDateTime2Date(enterTimeEnd.get()));
            queryBean.setQuery(eTransfer);
            getTableData();
        });

        //导出
        exportButton.setOnAction(event -> {
            ETransfer eTransfer = new ETransfer();

            eTransfer.setTransferNumber(queryNumberTextField.getText());
            eTransfer.setLicensePlate(StringUtils.isEmpty(queryLprComboBox.getValue())?null:queryLprComboBox.getValue());
            eTransfer.setWarehouseName(StringUtils.isEmpty(queryWarehouseComboBox.getValue())?null:queryWarehouseComboBox.getValue());
            eTransfer.setWarehouse1Name(StringUtils.isEmpty(queryWarehouse1ComboBox.getValue())?null:queryWarehouse1ComboBox.getValue());
            eTransfer.setGoodsName(StringUtils.isEmpty(queryGoodsComboBox.getValue())?null:queryGoodsComboBox.getValue());
            eTransfer.setGoods1Name(StringUtils.isEmpty(queryGoods1ComboBox.getValue())?null:queryGoods1ComboBox.getValue());
            eTransfer.setChargemanName(StringUtils.isEmpty(queryChargemanComboBox.getValue())?null:queryChargemanComboBox.getValue());
            eTransfer.setStatus(queryStautsComboBox.getValue()==null?null:queryStautsComboBox.getValue().getCode());

            if(!enterTimeStartPicker.isVoid())
                eTransfer.setEnterTimeStart(DateUtil.localDateTime2Date(enterTimeStart.get()));
            if(!enterTimeEndPicker.isVoid())
                eTransfer.setEnterTimeEnd(DateUtil.localDateTime2Date(enterTimeEnd.get()));
            queryBean.setQuery(eTransfer);
            exportExcel((Stage) ((Node) event.getSource()).getScene().getWindow());
        });
    }

    /**
     * 清空详情区
     */
    private void resetForm() {
        numberTextField.clear();
        lprTextField.clear();
        warehouseTextField.clear();
        warehouse1TextField.clear();
        goodsTextField.clear();
        goods1TextField.clear();
        chargemanTextField.clear();
        grossWeightTextField.clear();
        tareWeightTextField.clear();
        impurityWeightTextField.clear();
        netWeightTextField.clear();
        priceTextField.clear();
        deductionMoneyTextField.clear();
        amountTextField.clear();
        remarkTextField.clear();
        statusTextField.clear();
        enterTimeTextField.clear();
        outTimeTextField.clear();
        eTransferBinder=null;
    }

    /**
     * 初始化列表
     */
    private void initTable() {
        //设置列
        List<TableColumn<ETransfer, Object>> tableColumns = new LinkedList<>();
        for (TableColumnBean tcb : tableColumnBeans){
            TableColumn<ETransfer, Object> tableColumn = new TableColumn<>(tcb.getColumnName());
            tableColumn.setCellValueFactory(new PropertyValueFactory<>(tcb.getRecordName()));
            tableColumn.setSortable(tcb.isSort());
            tableColumn.setVisible(tcb.isVisible());
            tableColumn.setCellFactory(eTransferObjectTableColumn -> {
                TableCell<ETransfer, Object> cell = new TableCell<>(){
                    @Override
                    protected void updateItem(Object o, boolean b) {
                        super.updateItem(o, b);
                        if(b || o==null){
                            this.setText(null);
                        }else {
                            this.setText(tcb.format(o));
                        }
                    }
                };
                cell.setAlignment(Pos.CENTER);
                return cell;
            });
            tableColumns.add(tableColumn);
        }
        tableView.getColumns().addAll(tableColumns);//添加列

        //设置双击某一列
        tableView.setRowFactory(tableView -> {
            TableRow<ETransfer> row = new TableRow<>();
            row.setOnMouseClicked(mouseEvent -> {
                if(mouseEvent.getClickCount()==2 && !row.isEmpty()){
                    eTransferBinder = row.getItem();
                    autoForm(eTransferBinder);
                }
            });
            return row;
        });

        tableView.setSortPolicy(tableView -> {
            ObservableList<TableColumn<ETransfer,?>> list = tableView.getSortOrder();
            if(list!=null && !list.isEmpty()){
                String orderby = "";
                for (TableColumn<ETransfer,?> tableColumn: list){
                    String property = ((PropertyValueFactory)tableColumn.getCellValueFactory()).getProperty();
                    TableColumn.SortType sortType = tableColumn.getSortType();
                    if(sortType == TableColumn.SortType.DESCENDING) property += " desc";
                    orderby += property+",";
                }
                orderby = orderby.substring(0, orderby.length()-1);
                if(StringUtils.isNotEmpty(orderby)) queryBean.setOrderBy(orderby);
                getTableData();
            }
            return true;
        });

        //每页显示多少条数据
        pageSizeChiceBox.getItems().addAll(5,10,20,50,100,150,200);
        pageSizeChiceBox.setValue(queryBean.getPageSize());

        pagination.setMaxPageIndicatorCount(9);//数字按钮数量

        //获取表格数据
        getTableData();
    }

    /**
     * 填充显示详情区
     * @param eTransferBinder
     */
    private void autoForm(ETransfer eTransferBinder) {
        if(eTransferBinder==null) return;
        numberTextField.setText(eTransferBinder.getTransferNumber());
        lprTextField.setText(eTransferBinder.getLicensePlate());
        warehouseTextField.setText(eTransferBinder.getWarehouseName());
        warehouse1TextField.setText(eTransferBinder.getWarehouse1Name());
        goodsTextField.setText(eTransferBinder.getGoodsName());
        goods1TextField.setText(eTransferBinder.getGoods1Name());
        chargemanTextField.setText(eTransferBinder.getChargemanName());
        grossWeightTextField.setText(defDouble2Str(eTransferBinder.getGrossWeight(),"0.0"));
        tareWeightTextField.setText(defDouble2Str(eTransferBinder.getTareWeight(),"0.0"));
        impurityWeightTextField.setText(defDouble2Str(eTransferBinder.getImpurityWeight(),"0.0"));
        netWeightTextField.setText(defDouble2Str(eTransferBinder.getNetWeight(),"0.0"));
        priceTextField.setText(defDouble2Str(eTransferBinder.getPrice(),"0.0"));
        deductionMoneyTextField.setText(defDouble2Str(eTransferBinder.getDeductionMoney(),"0.0"));
        amountTextField.setText(defDouble2Str(eTransferBinder.getPaymentAmount(),"0.0"));
        remarkTextField.setText(eTransferBinder.getRemark1());
        statusTextField.setText(showStatus(eTransferBinder.getStatus()));
        enterTimeTextField.setText(DateUtil.date2String(eTransferBinder.getEnterTime(), DateUtil.YYYY_MM_DD_HH_MM_SS));
        outTimeTextField.setText(DateUtil.date2String(eTransferBinder.getOutTime(), DateUtil.YYYY_MM_DD_HH_MM_SS));
    }

    private String showStatus(Integer status) {
        if(status==null) return null;
        switch (status){
            case 0:return "作废";
            case 1:return "过磅完成";
            case 2:return "确认完成";
            default:return status.toString();
        }
    }

    private String defDouble2Str(Double num, String def){
        if(num==null){
            return def;
        }else {
            return num.toString();
        }
    }

    /**
     * 获取表格数据
     */
    private void getTableData() {
        if(StringUtils.isEmpty(queryBean.getOrderBy())){
            queryBean.setOrderBy("enter_time desc");
        }
        AppRequest.getInstance().getService().queryTransfer(queryBean)
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取内部周转记录列表") {
                    @Override
                    protected void onHandleSuccess(PageInfo<ETransfer> pageInfo) {
                        runLater(()->{
                            //总页数发生改变时从第一页开始
                            if(queryBean.getPageNum()>pageInfo.getPages() && queryBean.getPageNum()!=1 ){
                                queryBean.setPageNum(1);
                                getTableData();
                                return;
                            }

                            //一共多少条数据
                            if(queryBean.getTotal()-pageInfo.getTotal()!=0){
                                queryBean.setTotal(pageInfo.getTotal());
                                totalLabel.setText(String.valueOf(queryBean.getTotal()));
                            }

                            //一共多少页
                            if(queryBean.getPages()-pageInfo.getPages()!=0) {
                                queryBean.setPages(pageInfo.getPages());
                                pagesLabel.setText(String.valueOf(queryBean.getPages()));
                                pagination.setPageCount(queryBean.getPages());
                            }

                            tableView.getItems().clear();
                            if(pageInfo.getList()!=null && !pageInfo.getList().isEmpty())
                                tableView.getItems().addAll(pageInfo.getList());
                        });
                    }
                });
    }

    /**
     * 导出电子表格
     */
    private void exportExcel(Stage stage) {
        if(StringUtils.isEmpty(queryBean.getOrderBy())){
            queryBean.setOrderBy("enter_time desc");
        }
        AppRequest.getInstance().getService().queryTransfer(queryBean)
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取内部周转记录列表") {
                    @Override
                    protected void onHandleSuccess(PageInfo<ETransfer> pageInfo) {
                        runLater(()->{
                            //总页数发生改变时从第一页开始
                            if(queryBean.getPageNum()>pageInfo.getPages() && queryBean.getPageNum()!=1 ){
                                queryBean.setPageNum(1);
                                getTableData();
                                return;
                            }

                            //一共多少条数据
                            if(queryBean.getTotal()-pageInfo.getTotal()!=0){
                                queryBean.setTotal(pageInfo.getTotal());
                                totalLabel.setText(String.valueOf(queryBean.getTotal()));
                            }

                            //一共多少页
                            if(queryBean.getPages()-pageInfo.getPages()!=0) {
                                queryBean.setPages(pageInfo.getPages());
                                pagesLabel.setText(String.valueOf(queryBean.getPages()));
                                pagination.setPageCount(queryBean.getPages());
                            }

                            if(pageInfo.getList()!=null && !pageInfo.getList().isEmpty()){
                                DirectoryChooser directoryChooser=new DirectoryChooser();
                                directoryChooser.setTitle("选择本地目录保存电子表单");
                                directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")));
                                File dir = directoryChooser.showDialog(stage);

                                // 声明一个工作薄
                                HSSFWorkbook workbook = new HSSFWorkbook();
                                // 生成一个表格
                                HSSFSheet sheet = workbook.createSheet("内部周转记录");

                                // 产生表格标题行
                                HSSFRow row = sheet.createRow(0);
                                row.setHeightInPoints(15); //设置表头高度
                                // 第四步，创建表头单元格样式 以及表头的字体样式
                                HSSFCellStyle headStyle = workbook.createCellStyle();
                                headStyle.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
                                HSSFFont headerFont = workbook.createFont(); // 创建字体样式
                                headerFont.setFontName("黑体"); // 设置字体类型
                                headerFont.setFontHeightInPoints((short) 12); // 设置字体大小
                                headStyle.setFont(headerFont); // 为标题样式设置字体样式
                                for (short i = 0; i < tableColumnBeans.length; i++) {
                                    HSSFCell cell = row.createCell(i);
                                    cell.setCellStyle(headStyle);
                                    HSSFRichTextString text = new HSSFRichTextString(tableColumnBeans[i].getColumnName());
                                    cell.setCellValue(text);
                                }

                                HSSFCellStyle dateStyle = workbook.createCellStyle();
                                CreationHelper createHelper=workbook.getCreationHelper();
                                dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyy-mm-dd hh:mm:ss"));

                                List<ETransfer> eBuys = pageInfo.getList();
                                for(int i=0;i<eBuys.size();i++){
                                    ETransfer transfer = pageInfo.getList().get(i);
                                    row = sheet.createRow(i+1);

                                    HSSFCell cell = row.createCell(0);
                                    cell.setCellValue(transfer.getTransferNumber());
                                    cell = row.createCell(1);
                                    cell.setCellValue(transfer.getLicensePlate());
                                    cell = row.createCell(2);
                                    cell.setCellValue(transfer.getWarehouseName());
                                    cell = row.createCell(3);
                                    cell.setCellValue(transfer.getWarehouse1Name());
                                    cell = row.createCell(4);
                                    cell.setCellValue(transfer.getGoodsName());
                                    cell = row.createCell(5);
                                    cell.setCellValue(transfer.getGoods1Name());
                                    cell = row.createCell(6);
                                    cell.setCellValue(transfer.getGrossWeight());
                                    cell = row.createCell(7);
                                    cell.setCellValue(transfer.getTareWeight());
                                    cell = row.createCell(8);
                                    cell.setCellValue(transfer.getImpurityWeight()==null?0d:transfer.getImpurityWeight());
                                    cell = row.createCell(9);
                                    cell.setCellValue(transfer.getNetWeight());
                                    cell = row.createCell(10);
                                    cell.setCellValue(transfer.getPrice()==null?0d:transfer.getPrice());
                                    cell = row.createCell(11);
                                    cell.setCellValue(transfer.getDeductionMoney()==null?0d:transfer.getDeductionMoney());
                                    cell = row.createCell(12);
                                    cell.setCellValue(transfer.getPaymentAmount()==null?0d:transfer.getPaymentAmount());
                                    cell = row.createCell(13);
                                    cell.setCellValue(transfer.getWeighmanName());
                                    cell = row.createCell(14);
                                    cell.setCellValue(transfer.getChargemanName());
                                    cell = row.createCell(15);
                                    cell.setCellValue(showStatus(transfer.getStatus()));
                                    cell = row.createCell(17);
                                    cell.setCellStyle(dateStyle);
                                    cell.setCellValue(transfer.getEnterTime());
                                    cell = row.createCell(18);
                                    cell.setCellStyle(dateStyle);
                                    cell.setCellValue(transfer.getOutTime());
                                }

                                try {
                                    String reportPath = dir.getPath()+"/内部周转记录.xls";
                                    OutputStream out = new FileOutputStream(reportPath);
                                    workbook.write(out);
                                    out.close();
                                    Runtime.getRuntime().exec("rundll32 url.dll FileProtocolHandler "+ reportPath);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                });
    }
}
